package com.happe.foodeasy.controller.base;

import com.alibaba.fastjson.JSON;
import com.happe.foodeasy.dto.CustomerDto;
import com.happe.foodeasy.service.CustomerService;
import com.happe.foodeasy.util.ResultEntity;
import com.happe.foodeasy.util.ValidateResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private CustomerService customerService;

    /**
     * check username is  existent or not, then use the response to write
     * the result to frontend. True result means not existent, false means
     * existent
     *
     * @param username the name should be checked
     * @param response write the result to frontend
     */
    @RequestMapping("/checkUsername")
    public void checkUsername(String username, HttpServletResponse response) {
        boolean result = customerService.checkUsernameExist(username);
        String resultJson = JSON.toJSONString(new ResultEntity(!result ? ValidateResultEnum.SUCCESS.toString() : ValidateResultEnum.DEFEAT.toString()));
        try {
            response.getWriter().write(resultJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/register")
    public void register(CustomerDto customerDto, HttpServletResponse response) {
        customerDto.setCreateTime(new Date());
        customerService.saveOne(customerDto);
        try {
            response.getWriter().write(JSON.toJSONString(new ResultEntity(ValidateResultEnum.SUCCESS.toString())));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/loginIn")
    public void loginIn(CustomerDto customerDto, HttpServletResponse response) {
        boolean result = customerService.checkUserExist(customerDto);
        String jsonResult = JSON.toJSONString(new ResultEntity(result));
        try {
            response.getWriter().write(jsonResult);
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    @SuppressWarnings("all")
    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }
}
